package com.zl.Sqlite.db;

import android.content.Context;

import java.util.*;

/**
 * User: c3t
 * Date: 14-5-2
 * Time: 上午5:10
 */
public class UserDaoApi {
    private SQLiteTemplateByAPI sqLiteTemplateByAPI;

    public UserDaoApi(Context context) {
        sqLiteTemplateByAPI = new SQLiteTemplateByAPI(context);
    }

    /**
     * 添加一个用户
     *
     * @param name 要添加的用户名
     */
    public void add(String name) {
        Map map = new HashMap();
        map.put("name", name);
        sqLiteTemplateByAPI.add(map, "user");
    }

    /**
     * 查找用户是否存在
     *
     * @param name 要查找的用户名
     */
    public boolean find(String name) {
       return sqLiteTemplateByAPI.find(name, "user").isExist();
    }

    /**
     * 更新用户名
     *
     * @param name 新用户名
     * @param id   被更新用户id
     */
    public void update(String name, String id) {
        Map map = new HashMap();
        map.put("name", name);
        sqLiteTemplateByAPI.update(map, "user", " id = ? ", new String[]{id});
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    public void delete(String id) {
        sqLiteTemplateByAPI.delete("user", " id = ? ", new String[]{id});
    }

    /**
     * 得到所有用户
     *
     * @return
     */
    public List<User> findAll() {
        ResulstObject ro = sqLiteTemplateByAPI.findAll("user", new String[]{"id", "name"}, null, null, null, null, null);
        List<User> users = new ArrayList<>();
        List list = ro.getResult();
        for (int i = 0; i < list.size(); i++) {
            Map m = (Map) list.get(i);
            User u = new User(Integer.valueOf(String.valueOf(m.get("id"))), String.valueOf(m.get("name")));
            users.add(u);
        }
        return users;
    }
}
